package yxy.game.pm2.command.passbarrier;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PassBarrierMessage;
import yxy.game.pm2.module.passbarrier.PassbarrierHandle;
import yxy.game.pm2.module.passbarrier.PassbarrierPlayerModule;
import yxy.game.pm2.module.passbarrier.PassbarrierRank;

import java.util.Collection;


/****************************************
 * @name CMD_PassBarrierRank
 * @description 斩关夺隘主排行榜
 * @author 梁健彬
 * @since 2022-09-05
 ***************************************/
@MessageType(proto = Command.PassBarrierRank, classtype = PassBarrierMessage.PassBarrierRankRequest.class)
public class CMD_PassBarrierRank extends Command<PassBarrierMessage.PassBarrierRankRequest> {

    @Override
    public void execute(MessageSource messageSource, PassBarrierMessage.PassBarrierRankRequest request) throws Exception {
        String playerCode = messageSource.getTag();
        PassBarrierMessage.PassBarrierRankResponse.Builder response = PassBarrierMessage.PassBarrierRankResponse.newBuilder();
        try {
            PassbarrierPlayerModule module = PassbarrierPlayerModule.get(playerCode);
            if (module == null) {
                send(messageSource, response, Result.DataError);
                return;
            }

            PassbarrierRank currentRank = PassbarrierRank.getRank(playerCode, PassbarrierRank.currentDayScore); //当天排行榜
            PassbarrierRank totalRank = PassbarrierRank.getRank(playerCode, PassbarrierRank.totalScore); //全部总和排行榜

            Collection<RankEntry> currentTop = currentRank.top(currentRank.topSize());//当天的前50条
            Collection<RankEntry> totalTop = totalRank.top(totalRank.topSize());//全部前50条

            PassbarrierHandle handle = new PassbarrierHandle();
            //todo 返回日排行 周排行 以及个人排行
            handle.packRank(playerCode, currentTop, currentRank, PassbarrierRank.currentDayScore, response);
            handle.packRank(playerCode, totalTop, totalRank, PassbarrierRank.totalScore, response);

            send(messageSource, response, Result.Success);
        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);
        }
    }

    private void send(MessageSource messageSource, PassBarrierMessage.PassBarrierRankResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }


}
